from django import forms
from django.core.validators import RegexValidator
from utils.encrypt import md5_string
from utils.bootstrap_form import BootstrapForm


class Login(BootstrapForm, forms.Form):
    """ 用户名密码登录表单 """
    role = forms.ChoiceField(
        label="角色",
        choices=(("1", "管理员"), ("2", "客户"))  # 谁在前默认是谁
    )
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True)
    )

    def clean_password(self):
        old = self.cleaned_data['password']
        return md5_string(old)

    # 也可以用init方法设置role的指定默认值
    # def __init__(self, *args, **kwargs):
    #     super().__init__(*args, **kwargs)
    #     # 设置role字段的初始值为"1"，也就是对应"管理员"选项
    #     self.fields['role'].initial = "1"


class SmsLogin(BootstrapForm, forms.Form):
    """ 短信登录表单 """
    role = forms.ChoiceField(
        label="角色",
        choices=(("1", "管理员"), ("2", "客户"))
    )
    mobile = forms.CharField(
        label="电话号",
        validators=[RegexValidator(r'^1[3579]\d{9}$', '手机号格式错误')],
        widget=forms.TextInput
    )
    code = forms.CharField(
        label="验证码",
        validators=[RegexValidator(r'\d{4}', '请输入4位有效数字')],
        widget=forms.TextInput
    )


class SendSms(forms.Form):
    """ 发送短信表单 """
    role = forms.ChoiceField(
        label="角色",
        choices=(("1", "管理员"), ("2", "客户"))
    )
    mobile = forms.CharField(
        label="电话号",
        validators=[RegexValidator(r'^1[3579]\d{9}$', "手机号格式错误")]
    )
